package memberrewards.service;

import hackathon1212.ServletPojoAdapter;

import java.util.HashMap;
import java.util.Map;
import memberrewards.delegate.RewardsDelegate;
import memberrewards.dtos.AccountDetailDTO;
import memberrewards.dtos.TierConfigDTO;

/**
 * Servlet implementation class RedeemCash
 */
public class RedeemCash extends ServletPojoAdapter {
	private static final long serialVersionUID = -1625009494230982846L;

	protected Map<String,String> getBusinessMethod(Map<String, String[]> params){
		//Query Params
		final String pan =params.get("pan")!=null? params.get("pan")[0]:null;
		final String cashVal =params.get("cashval")!=null? params.get("cashval")[0]:null;
		
		//Default response
		final Map<String,String> ret = new HashMap<String, String>();
		ret.put("status", "Card Not Found");		
		ret.put("balance", "0");
		final AccountDetailDTO accountDetail = RewardsDelegate.getAccountDetail(pan);
		if (accountDetail!=null) {
			final TierConfigDTO tierConfig = accountDetail.getTierConfig();
			final int pointsBalance = new Integer(accountDetail.getPointBalance());
			try{
				final Double cashToRedeem = new Double(cashVal);
				final Double cpp = new Double (tierConfig.getCostPerPoint());
				final Double pointstoRedeem = cashToRedeem / cpp;	
				if(pointstoRedeem.intValue() <= pointsBalance){
					int newPointBalance=	pointsBalance - pointstoRedeem.intValue();
					accountDetail.setPointBalance(Integer.toString(newPointBalance));
					boolean status=RewardsDelegate.updateAccountDetail(accountDetail);
					System.out.println(getClass().getName()+" UpdateStatus ::"+status);
					ret.put("balance", Integer.toString(newPointBalance));
					ret.put("status", "Success");
				}
				else{
					ret.put("status", "Insufficient Points");
				}
			}
			catch(Exception ex){
				ret.put("status", "Invalid Cash value");
			}
		}
		return ret;
	}
}
